using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Web;

namespace sgf.server
{
    public class KestrelNetServer
    {
        private WebApplication app { get; set; }

        public async Task Start(int port, Action<NetChannel> onConnect, Action<long, byte[]> onMessage,
            Action<NetChannel> onDisConnect)
        {
            var builder = WebApplication.CreateBuilder();

            builder.Services.AddSingleton<TcpConnectionHandler>(_ =>
                new TcpConnectionHandler(onConnect, onMessage, onDisConnect));
            builder.WebHost.UseKestrel(options =>
                {
                    options.ListenAnyIP(port,
                        configBuilder => { configBuilder.UseConnectionHandler<TcpConnectionHandler>(); });
                })
                .ConfigureLogging(logging => { logging.SetMinimumLevel(LogLevel.Error); })
                .UseNLog();
            app = builder.Build();
            LogMgr.Info("监听TCP端口: " + port);
            await app.StartAsync();
        }
    }
}